package com.zjoin.study.arithmetic.基础.字符串;

import java.util.Arrays;

/**
 * 类名 外观数列
 * 描述
 *
 * @Author xwyang
 * @Date 2020/8/24 14:46
 * @Version 1.0
 **/
public class 外观数列 {
    
    /**
     * 1.     1
     * 2.     11
     * 3.     21
     * 4.     1211
     * 5.     111221
     * 6.     312211
     * 7.     13112221
     * 8.     1113213211
     *
     * @param n
     * @return
     */
    
    
    public static String countAndSay(int n) {
        if (n < 0) {
            return null;
        }
        if (n == 1) {
            return "1";
        }
        String[] arr = new String[n];
        Arrays.fill(arr, "");
        arr[0] = "1";
        
        for (int i = 1; i < n; i++) {
            String s = arr[i - 1];
            if (s.length() == 1) {
                arr[i] = "11";
            } else {
                String[] chars = s.split("");
                int l = 0;
                for (int m = 1; m < chars.length; ) {
                    String x = chars[l];
                    String y = chars[m];
                    if (!x.equals(y)) {
                        arr[i] += (m - l) + x;
                        l = m;
                    }
                    if (m == chars.length - 1) {
                        arr[i] += (m - l + 1) + y;
                    }
                    m++;
                    
                }
            }
        }
        return arr[n - 1];
    }
    
    public static void main(String[] args) {
//        System.out.println(countAndSay(2));
        System.out.println(countAndSay(5));
    }
}
